package com.dayou.interceptor;

import com.dayou.config.cors.CorsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private ServiceInterceptor loginInterceptor;
    @Autowired
    private CorsFilter corsFilter;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    //配置静态资源，比如html，js，css，等等
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
    //写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(loginInterceptor);
        //拦截路径，表示此路径下的所有地址都会先执行此拦截器，通过之后才能访问Controller
        String[] addPathPatterns = {"/**"};
        //拦截
        String[] excludePaths = new String[]{"/","/login","/index","/logout","/interview","/interview/login","/static/**","/interview/lawyerEntry","/interview/comparisonBringRecords","/bringRecord/edit","/request/*","/prisoner/listByIds"};
        addInterceptor.addPathPatterns(addPathPatterns).excludePathPatterns(excludePaths);
    }

    /**
     * 注册 cors filter
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(corsFilter);
        registration.addUrlPatterns("*");
        registration.setName("corsFilter");
        registration.setOrder(1);
        return registration;
    }
}
